package me.xiaoyan.android.tuition.activity.core;

import java.util.HashMap;
import java.util.Map;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityGroup;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

@SuppressLint("UseSparseArrays")
public abstract class MainActivity extends ActivityGroup {

	/** 用来加载子Activity的布局 */
	private LinearLayout container = null;

	/** 选项卡 */
	private RadioGroup radioGroup = null;

	/** 选中标签的ID */
	private int radioGroupCheckId;

	/** 切换标签动作的标志位 */
	private boolean changedFlag;

	/** 选项卡的所有标签 */
	private RadioButton[] radioButtons = null;
	/** 源Intent */
	protected Intent fromIntent;

	/** 功能模块跳转的目标Intent */
	protected Intent targetIntent = new Intent();

	private int[] radioButtonIds;
	private int[] radioButtonImageIds;
	private int[] radioButtonTexts;

	/** 标签ID对应的初始Activity集合 */
	private Map<Integer, Class<? extends Activity>> classes = new HashMap<Integer, Class<? extends Activity>>();

	/** 标签ID对应的当前Activity集合 */
	public Map<Integer, Class<? extends Activity>> currentClasses = new HashMap<Integer, Class<? extends Activity>>();;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (getLayoutResourceId() <= 0) {
			throw new NullPointerException("not set contentview layout");
		}

		setContentView(getLayoutResourceId());
		fromIntent = getIntent();
		initRadioGroupData();
		initWidgetStatic();

	}

	/** 设定数据源的方法 */
	protected void initRadioGroupData() {
		radioButtonIds = getRadioButtonIds();
		radioButtonImageIds = getRadioButtonImageIds();
		radioButtonTexts = getRadioButtonTexts();
		if (radioButtonIds == null) {
			throw new NullPointerException("請設置radiobutton");
		}

		for (int i = 0; i < radioButtonIds.length; i++) {
			classes.put(radioButtonIds[i], getClasses()[i]);
			currentClasses.put(radioButtonIds[i], getClasses()[i]);
		}
	}

	/** 初始化控件 */
	protected void initWidgetStatic() {
		container = (LinearLayout) findViewById(getContentContainerId());
		radioGroup = (RadioGroup) findViewById(getRadioGroupId());
		radioButtons = new RadioButton[radioButtonIds.length];

		for (int i = 0; i < radioButtons.length; i++) {
			radioButtons[i] = (RadioButton) findViewById(radioButtonIds[i]);
			// 设置图片及文字
			if (radioButtonImageIds != null) {
				radioButtons[i].setText(radioButtonTexts[i]);
				Drawable drawable = getResources().getDrawable(
						radioButtonImageIds[i]);
				radioButtons[i].setCompoundDrawablesWithIntrinsicBounds(null,
						drawable, null, null);
			}
			// 设置点击事件
			radioButtons[i].setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					if (!changedFlag) {
						targetIntent.setClass(MainActivity.this,
								classes.get(radioGroupCheckId));
						launchActivity(targetIntent);
					}
					changedFlag = false;
				}
			});
		}

		// 给选项卡设定监听
		radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(RadioGroup group, int checkedId) {
				currentClasses.put(radioGroupCheckId, MainActivity.this
						.getCurrentActivity().getClass());
				setTargetIntent(checkedId);
				launchActivity(targetIntent);
				radioGroupCheckId = checkedId;
				changedFlag = true;
			}
		});

		// 初始化加载
		radioGroupCheckId = getCheckedRadioButtonId();
		setTargetIntent(radioGroupCheckId);
		launchNewActivity(targetIntent);
	}

	/** ActivityGroup加载子Activity的方法(先看有没有，有则加载原来的，否则创建新的) */
	public void launchActivity(Intent intent) {
		container.removeAllViews();
		container.addView(getLocalActivityManager().startActivity(
				intent.getComponent().getShortClassName()
						+ getCheckedRadioButtonId(),
				intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP))
				.getDecorView());
	}

	/** 设定目标Intent的方法 */
	protected void setTargetIntent(int checkedId) {
		targetIntent.setClass(this, currentClasses.get(checkedId));
	}

	/** ActivityGroup加载新的子Activity的方法(创建新的) */
	public void launchNewActivity(Intent intent) {
		
		container.removeAllViews();
		
		View view = getLocalActivityManager().startActivity(
				intent.getComponent().getShortClassName()
						+ getCheckedRadioButtonId(),
				intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
		//Animation anim = AnimationUtils.loadAnimation(this, R.anim.in);
		//view.startAnimation(anim);
		container.addView(view);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getKeyCode() == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_UP) { // 处理返回键
			if (event.getRepeatCount() == 0) {
				getCurrentActivity().onBackPressed();
			}
			return false;
		}
		return super.dispatchKeyEvent(event);
	}

	/** ActivityGroup加载新的子Activity的方法(创建新的) */
	public void launchNewActivityForResult(ChildActivity requestSubActivity,
			Intent intent, int requestCode) {
		intent.putExtra("requestCode", requestCode);
		container.removeAllViews();
		container
				.addView(getLocalActivityManager().startActivity(
						intent.getComponent().getShortClassName()
								+ getCheckedRadioButtonId(),
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
						.getDecorView());
		((ChildActivity) getCurrentActivity())
				.setRequestSubActivity(requestSubActivity);
	}

	/** 这个方法用于获取当前ActivityGroup的选项卡按下的单选按钮的ID */
	public int getCheckedRadioButtonId() {
		return radioGroup.getCheckedRadioButtonId();
	}

	/** 設置當前view的佈局文件ID */
	protected abstract int getLayoutResourceId();

	/** 选项卡所有标签的ID */
	protected abstract int[] getRadioButtonIds();

	/** 选项卡所有标签的图标 */
	protected abstract int[] getRadioButtonImageIds();

	/** 选项卡所有标签的文字 **/
	protected abstract int[] getRadioButtonTexts();

	/** 在子类中需要实现的获取选项卡所有标签ID对应的初始Activity的方法 */
	public abstract Class<Activity>[] getClasses();

	protected int getContentContainerId() {
		return 0;
	}

	protected int getRadioGroupId() {
		return 0;
	}
}
